﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Loong.Authentication;

namespace Loong.AspNetCore.Authentication
{
    public static class AuthenticationExtensions
    {
        public static IServiceCollection AddJwtBearer(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var tokenOptions = new JwtTokenOptions();
                configuration.Bind(tokenOptions);

                options.TokenValidationParameters.ValidAudience = tokenOptions.ValidAudience;
                options.TokenValidationParameters.ValidIssuer = tokenOptions.ValidIssuer;
                options.TokenValidationParameters.IssuerSigningKey = tokenOptions.GetSecurityKey();
            });

            services.AddTransient<IJwtTokenService, JwtTokenService>();
            services.Configure<JwtTokenOptions>(configuration);

            return services;
        }
    }
}
